package com.wen.yygh.cmn.serivce.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wen.yygh.cmn.listener.DictListener;
import com.wen.yygh.cmn.mapper.DictMapper;
import com.wen.yygh.cmn.serivce.DictService;
import com.wen.yygh.model.cmn.Dict;
import com.wen.yygh.vo.cmn.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Wenjl
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //吧查询内容添加到缓存
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        //像list结合中每个dict对象中设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild =this.isChildren(dictId);
            dict.setHasChildren(isChild);

        }
        return dictList;
    }

    /**
     * 导出
     *
     * @param response
     * @throws IOException
     */
    @Override
    public void exportDictData(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }

        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("sheet1")
                .doWrite(dictEeVoList);
    }

    /**
     * 导入
     *
     * @param file
     */
    //清空缓存
    @CacheEvict(value = "dict", allEntries = true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String findNameByDictCodeWithValue(String dictCode, String value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(dictCode)) {
            //如果dictCode不为空
            Long parent_id = getDictByDictCode(dictCode).getId();
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value)
            );

            return dict.getName();


        } else {
            wrapper.eq("value", value);
            String name = baseMapper.selectOne(wrapper).getName();
//            log.info("name=>"+name);

            return name ;
        }


    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper();
        //如果dictCode不为空
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    @Override
    public String findNameByValue(String value) {
        return findNameByDictCodeWithValue(null, value);
    }

    @Override
    public List<Dict> findNameByDictCode(String dictCode) {
        //根据dictcode获取指定对象
        Dict dict = getDictByDictCode(dictCode);

        //根据id获取子节点
        return findChildData(dict.getId());
    }

    /**
     * 判断有没有子节点
     *
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
